package org.example.rocketmq.delay;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

public class Consumer {
    public static void main(String[] args) throws MQClientException {
        receive("1");
    }

    /**
     * 消费模式
     *  1. 广播模式 消息将发送到同一个消费者组中所有的消费者
     *  2. 负载均衡 消息只能发送到一个组中的某一个消费者（默认使用负载均衡模式）
     * @return
     * @throws MQClientException
     */
    public static DefaultMQPushConsumer getConsumer(String name) throws MQClientException {
        //1. 创建消费者并指定消费者组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-group1");
        //2. 指定namesrv
        consumer.setNamesrvAddr("192.168.3.109:9876;192.168.3.108:9876");
        //3. 订阅主题和tag
        consumer.subscribe("delayTopic", "*");

        //指定instance-name   同一个组中的consumer  instance-name不能冲突
        consumer.setInstanceName("consumer"+name);

        //设置消费模式 负载均衡/广播模式  MessageModel.CLUSTERING/MessageModel.BROADCASTING
//        consumer.setMessageModel(MessageModel.CLUSTERING);

        return consumer;
    }

    public static void receive(String name) throws MQClientException {
        DefaultMQPushConsumer consumer = getConsumer(name);
        //设置消息接受的回调
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.println("consumer " + name + "  " + new String(msg.getBody()) + " 延时时间 ： "+(System.currentTimeMillis() - msg.getStoreTimestamp()));
                }
                //返回消息的消费结果
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //启动消费者
        consumer.start();
    }
}
